package com.community.util;

import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import java.io.IOException;
import java.io.StringWriter;

public class XmlUtil {

    private static OutputFormat outputFormat =null;

    public static OutputFormat getOutPutFormat(){
        if(outputFormat==null){
            outputFormat  = OutputFormat.createPrettyPrint();
            outputFormat.setEncoding("UTF-8");
            outputFormat.setIndent(true); //设置是否缩进
            outputFormat.setIndent("    "); //以四个空格方式实现缩进
            outputFormat.setNewlines(true); //设置是否换行
        }
        return outputFormat;
    }

    public static StringWriter formatDom(Document doc) throws IOException {
        // stringWriter字符串是用来保存XML文档的
        StringWriter stringWriter = new StringWriter();
        // xmlWriter是用来把XML文档写入字符串的(工具)
        XMLWriter xmlWriter = new XMLWriter(stringWriter, getOutPutFormat());
        // 把创建好的XML文档写入字符串
        xmlWriter.write(doc);
        xmlWriter.close();
        return stringWriter;
    }
}
